<template>
  <div class="tas-main">
    <!-- 风险源 -->
    <div class="source-class">
      <el-tabs v-model="approveStatus" @tab-click="tabClick">
        <el-tab-pane label="待审批" name="0"></el-tab-pane>
        <el-tab-pane label="审批完成" name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <sec-ext-table
      :reserveSelection="true"
      :rowKey="getRowId"
      :selection="true"
      :default-sort="sortProp"
      ref="secTableRef"
      @selection-change="handleSelectionChange"
      :tableData="tableData"
      :tableCol="tableCol"
      :loadingProp="loadingProp"
      :filterCol="filterCol"
      @filter-confirm="filterConfirm"
      @search-change="searchChange"
      @sort-change="sortChange"
    >
      <el-button type="primary" v-if="approveStatus === '0'" :disabled="isBatchDisable" @click="handleDeliver(null)"
        >批量转交</el-button
      >
      <template v-slot:leader="{ data }">
        <dc-user :name="data.row.leader"></dc-user>
      </template>
    </sec-ext-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="page"
      background
      :layout="layout"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      :total="totalSize"
    >
    </el-pagination>
    <!-- 转交 -->
    <el-dialog title="转交" append-to-body width="80%" @close="diaClose" :visible.sync="isShowDeliver">
      <account-change
        ref="accountChangeRef"
        v-if="isShowDeliver"
        :datas="selRows"
        :operateType="3"
        :isBatch="isBatch"
        @cancel="isShowDeliver = false"
        @confirm-success="deliverConfirmSuccess"
      ></account-change>
    </el-dialog>

    <!-- 处理 -->
    <el-dialog :title="title" append-to-body width="60%" :visible.sync="apiDiaShow"
      ><iframe
        style="width: 100%; height: 500px"
        id="h5-page"
        v-if="apiDiaShow"
        ref="iframeH5"
        :src="srcH5"
        frameborder="0"
        @load="loaded"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { paginationMixin } from "@/mixins/pagination";

import { getFeModelCfgList } from "api/riskCenterApi";
import {
  approveWorkListApi,
  receiveOrRejectApi,
  changeSensitivityWorkUser,
  governSensitivityWork,
  governSelfExamApi,
} from "api/taskCenterApi";

import accountChange from "components/accountChange";
import { approvalOpt } from "../model";

export default {
  name: "taskCenter",
  props: {},
  mixins: [paginationMixin],
  components: { accountChange },
  data() {
    return {
      isShowDeliver: false, //转交 是否展示
      approveStatus: "0",
      isBatch: false, //点击批量的操作/表格操作列
      selRows: [],
      sortProp: { prop: "createTime", order: "descending" }, //排序的数据
      tableData: [],
      tableCol: [],
      filterCol: [],
      //处理使用
      loadingProp: { selfInspect: false, handler: false },
      title: "",
      srcH5: "",
      apiDiaShow: false,
    };
  },
  computed: {
    isBatchDisable() {
      if (this.selRows.length == 0) return true;
      //appeal:1/3 申诉中/验收中
      return this.selRows.some((item) => item.appeal === "1");
    },
  },
  watch: {},
  mounted() {},
  async created() {
    this.operation = {
      type: "operation",
      label: "操作",
      width: 200,
      children: [
        ...approvalOpt.bind(this)(),
        {
          label: "详情",
          click: ({ row }) => {
            this.handleCheckDetail(row, true);
          },
        },
      ],
    };
    this.initPage();
  },
  methods: {
    isDisOptBtn(row) {
      return ["1", "3"].includes(row.appeal) ? true : false;
    },
    tabClick() {
      this.page = 1;
      this.initPage();
    },
    initPage() {
      this.initTableCol();
      this.initTableData();
      this.$nextTick(() => {
        //初始化筛选内容和搜索框数据
        //todo 如果搜素框输入完之后 直接去切换source 的tab会出现切换不了的情况。因为输入框失焦在了el-radio上
        this.searchVal = "";
        this.filter = [];
        this.$refs.secTableRef.reset(); //初始化选择框和筛选项以及字段设置
      });
    },
    getRowId(row) {
      return row.processId;
    },
    handleSelectionChange(val) {
      this.selRows = val;
    },
    searchChange(val) {
      this.searchVal = val;
      this.page = 1;
      this.initTableData();
    },
    filterConfirm(data) {
      this.filter = data;
      this.page = 1;
      this.initTableData();
    },
    initTableCol() {
      getFeModelCfgList({ source: "", type: "order" }).then((res) => {
        let data = res.data;
        console.log("[ data ] >", data);
        let { tableCol, filterCol } = new this.ConfigCondition({
          data: data,
          // exclude: ["uniqueId"],
          type: { slot: ["leader"] },
        });
        this.tableCol = tableCol;
        this.tableCol.push(this.operation);

        this.filterCol = filterCol;
      });
    },
    initTableData() {
      let loading = this.openLoading();
      let { prop, order } = this.sortProp;
      approveWorkListApi({
        approveStatus: this.approveStatus,
        pageNum: this.page,
        pageSize: this.pageSize,
        searchCnt: this.searchVal,
        filter: this.filter,
        orderField: prop, //排序字段
        sort: this.formatSort(order), //排序方式
      }).then((res) => {
        loading.close();
        this.tableData = res.data || [];
        this.totalSize = res.count;
      });
    },
    formatSort(orderParams) {
      if (!orderParams) return "";
      let order = "";
      if (orderParams == "ascending") {
        order = "asc";
      } else if (orderParams == "descending") {
        order = "desc";
      }
      return order;
    },
    sortChange({ column }) {
      //如果取消排序，把字段值也赋值成空
      let prop = column.order ? column.property : "";
      this.sortProp = { prop, order: column.order };
      this.initTableData();
    },

    handleCheckDetail(row, isDetail) {
      this.utils.$router(
        {
          path: `/task/${row.status}/${row.source}`,
          query: {
            type: row.type,
            processId: row.processId,
            uniqueId: row.uniqueId,
            caseId: row.caseId,
            isDetail,
          },
        },
        "_blank",
      );
    },
    // 转交
    handleDeliver(row) {
      this.isShowDeliver = true;
      this.isBatch = row ? false : true;
      this.selRows = row ? [row] : this.selRows;
    },
    // 转交 确定成功回调
    deliverConfirmSuccess(ruleForm) {
      let processIds = this.selRows.map((item) => item.processId);
      let { account, remark, businessKeep, businessLineName } = ruleForm;
      this.$refs.accountChangeRef.openBtnLoading();
      changeSensitivityWorkUser({
        account,
        remark,
        approveFlag: "1", //审批工单时才用到
        businessKeep,
        businessLineName: businessKeep === "0" ? businessLineName : "",
        processIds,
      }).then((res) => {
        this.$refs.accountChangeRef.closeBtnLoading();
        let state = this.message.state(res);
        if (!state) return;
        this.isShowDeliver = false;
        //列表界面调用
        this.reset?.();
      });
    },
    selfInspectionHandle(row) {
      this.title = "自查";
      this.$set(row, "loading", true);
      this.loadingProp.selfInspect = true;
      let processIds = [row.processId];
      governSelfExamApi({ processIds, type: row.type, source: row.source }).then((res) => {
        console.log("[ res ] >", res);
        this.srcH5 = res.data;
        this.loadingProp.selfInspect = false;
        this.$set(row, "loading", false);
        this.apiDiaShow = true;
      });
    },
    //处理
    handle(row) {
      this.title = "处理";
      //这两个属性决定这一个表格哪个行的哪个按钮展示loading
      if (row) {
        this.$set(row, "loading", true);
        this.loadingProp.handler = true;
      }
      governSensitivityWork({ processId: row.processId }).then((res) => {
        if (row) {
          this.$set(row, "loading", false);
          this.loadingProp.handler = false;
        }
        this.srcH5 = res.data;
        this.apiDiaShow = true;
        this.initTableData();
      });
    },
    loaded() {
      let oldAction = "";
      window.addEventListener(
        "message",
        (data) => {
          let action = data.data?.res?.action;
          if (action && action != oldAction) {
            oldAction = action;
            this.apiDiaShow = false;
            let loading = this.openLoading();
            setTimeout(() => {
              loading.close();
              //列表界面使用
              this.initPage?.();
              //详情调用
              this.refreshPage?.();
            }, 5000);
          }
          console.log("[ data ] >", data);
        },
        false,
      );
    },
    diaClose() {
      this.selRows = [];
      this.$refs.secTableRef.clearSelection();
    },
    reset() {
      this.selRows = [];
      this.$refs.secTableRef.clearSelection();
      this.initTableData();
    },
    // 页码变更
    handleCurrentChange(val) {
      this.page = val;
      this.initTableData();
    },
    // 条数变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.initTableData();
    },
  },
};
</script>
<style lang="scss" scoped>
.table-container {
  .btn {
    position: absolute;
    z-index: 1;
    right: 20px;
  }
}
.deliver-data {
  max-height: 400px;
  overflow: auto;
  margin-bottom: 20px;
}
</style>

<style scoped>
::v-deep .el-dialog__body {
  padding-top: 0 !important;
}
::v-deep .el-select {
  width: 100%;
}
</style>
